//
//  CHChatRoomBase.m
//  ChildHoodStemp
//
//  Created by lucky on 13-8-20.
//  Copyright (c) 2013年 __MyCompanyName__. All rights reserved.
//

#import "CHChatRoomBase.h"
#import "loginViewController.h"
#import "MicroDef.h"
#import "MBProgressHUD.h"
#import "ChildHoodMessage.h"
#import "ChildHoodUser.h"
#import "ChildHoodMemory.h"
#import "ChildHoodMemory.h"
#import "CHSVoiceRecorder.h"
#import "UIUtil.h"
#import "VoiceConverter.h"
#import "CHSAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "DetailInfo.h"
#import "CXmppMgr.h"
#import "MessageDao.h"
#import "CFolderMgr.h"
#import "CContactMgr.h"
#import <CoreData/CoreData.h>
#import "CXmppRequestMgr.h"
#import "CMessageMgr.h"
#import "CMessageModel.h"
#import "GroupMemberDetailVC.h"
#import "GroupDetailVC.h"
#import "MJRefresh.h"
#import "ChildHoodService.h"
#import "CFileModel.h"
#import "IMFileDownLoadController.h"
#import "MyInformationVC.h"
#import "MBProgressHUD+WZ.h"
#import "CMessageDraft.h"
#import "CMessageDraftMgr.h"
#import "CPresenceMgr.h"
#import "CPresenceModel.h"
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>
#import "ContactMessageSettingVc.h"
#import "ChatToolMoreView.h"
#import "UIBarButtonItem+category.h"
#import "EfengDiscussDetailController.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "CGroupModel.h"
#import "CGroupMgr.h"
#import "NSArray+PinYin.h"
#import "ChatToolMoreView.h"
#import "ChatBase.h"
#import "EFRootViewController.h"
#import "EFengTabController.h"
#import "WZNavigationController.h"
#import "ShowMapViewController.h"
#import "EFengVideoPlayerViewController.h"
#import "robRedPacketViewController.h"
#import "selfSendRedPacketViewController.h"
#import "redPacketResultViewController.h"
#import "redPacketInfoViewController.h"
#import "RedPacketInfo.h"
@interface CHChatRoomBase()<ABUnknownPersonViewControllerDelegate>
{
    ChildHoodMemory *_myChildHood;
    SNSPRelativeType _myRelativeType;
    CHSVoiceRecorder   *_recorder;
    UIView *freshView;
    //    EGORefreshTableHeaderView *_refreshHeaderView;
    
    NSString        *_myAudioFilePath;
    NSString        *_myAudioFileName;
    NSString        *_tempFileName;
    int64_t         _headID;
    int64_t         _tailID;
    
    //    BOOL            _reloading;
    
    NSInteger       _lastIndex;
    
    BOOL            _hasMsgRefreshNotic;
    //有没有新的通知
    BOOL            _hasNewGroupNotice;
    
    BOOL _isEnteredAndRefreshedView;
    NSArray *_messageFileArray;
}
//@property (retain, nonatomic)EGORefreshTableHeaderView *refreshHeaderView;
@property (copy, nonatomic) NSString *myAudioFilePath;
@property (copy, nonatomic) NSString *myAudioFileName;
@property (copy, nonatomic) NSString *tempFileName;
@property(nonatomic, retain)ContactsGroupMember *contactGroupMember;
@property(nonatomic, retain)ContactsGroup *contactGroup;
@property (nonatomic, strong) CContactModel *currentUser;
@property (nonatomic, strong) NSFetchedResultsController *resultControl;
@property (nonatomic, strong) CMessageModel *minMessage;
@property (nonatomic, strong) CMessageModel *maxMessage;
@property (nonatomic, assign) SNSPMaterialType sendType;
@property (nonatomic ,assign) NSInteger timeLenth;
@property (nonatomic, strong) NSString *messageContent;
@property (nonatomic, strong) UIImage *imageContent;
@property (nonatomic, assign) NSInteger imgIndex;
@property (nonatomic, assign) NSInteger fileIndex;
@property (nonatomic, strong) CFileModel *fileModel;
@property (nonatomic, strong) CContactMgr *conMgr;
@property (nonatomic, strong) CPresenceMgr *presenceMgr;
@property (nonatomic, strong) CMessageModel *firstUnreadMessage;

@property (nonatomic, strong) CGroupMgr *groupMgr;

@property (nonatomic, copy) NSString *serTimeStamp;
@property (nonatomic, assign) BOOL IsVoiceBtnUp;
@property (nonatomic, assign) BOOL IsGettingSerTime;


@property (nonatomic, strong) CMessageDraftMgr *messageDraftMgr;
@property (nonatomic, strong) CMessageMgr *messageMgr;

-(void)messageRefreshEvent:(NSNotification*)notification;
-(void)roomInfoEvent:(NSNotification*)notification;

@end

@implementation CHChatRoomBase
@synthesize timestamps = _timestamps;
@synthesize roomName = _roomName;
@synthesize childHoodRoom = _childHoodRoom;
//@synthesize refreshHeaderView = _refreshHeaderView;
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPUPDATEGROUPINFO object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPRECEIVEMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDSENDMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"REMOVEREDPOT_NOTICE" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"removeRedPoint" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPFAILEDRECEIVEMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDRECEIVEPRESENCE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MineDIdSendMessage" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DELRECORD" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RESENDMESSAGE" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"chsaudioPlayerPlayVoice" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"mutiViewDownLoadVoiceStatus" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDELETEUSER object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDeleteGroup object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CBEMOTIONSAVEPHONE object:nil];
    
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"IMFileManagerControllerDidSendFile" object:nil];
    _myChildHood = nil;
    self.member = nil;
    self.group = nil;
    NSLog(@"聊天窗口死了");
}




-(id)initWithRoomID:(int64_t)roomID
{
    self = [super init];
    if (self) {
        
        _messageRoomID = roomID;
    }
    return self;
}

-(id)initWithTargId:(int32_t)memoryId andClazz:(int32_t)clazzId
{
    self = [super init];
    if (self) {
        _teacherChat = NO;
        
        _targetMemoryId = memoryId;
        _targetClazzId  = clazzId;
    }
    return self;
}

-(id)initWithTeacherChat
{
    self = [super init];
    if (self) {
        _targetMemoryId = 0;
        _targetClazzId  = 0;
        _teacherChat = YES;
    }
    return self;
}


-(id)initWithTargID:(int32_t)memoryID andRoomName:(NSString *)roomname
{
    self = [super init];
    if (self) {
        _teacherChat = NO;
        _targetMemoryId = memoryID;
        [self.navigationItem setNewTitle:roomname];
        
    }
    return self;
}

- (void)back
{
    [[CHSAudioPlayer sharedInstance] stopSound];
    EFRootViewController *chatcontroler = nil;
    NSArray *controllerArray = self.navigationController.childViewControllers;
    for (UIViewController *controller in controllerArray) {
        if ([controller isKindOfClass:[EFRootViewController class]]) {
            chatcontroler = (EFRootViewController*)controller;
            break;
        }
    }
    EFengTabController *tabaar = nil;
    for (UIViewController *controller in chatcontroler.childViewControllers) {
        if ([controller isKindOfClass:[EFengTabController class]]) {
            tabaar = (EFengTabController*)controller;
            tabaar.selectedIndex = 0;
            break;
        }
    }
    if (chatcontroler) {
        [self.navigationController popToViewController:chatcontroler animated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"backFromChat" object:nil];
    }
    else
    {
    [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)enterClassDetail
{
    
}
-(void)openFullScreenPlayVido:(NSIndexPath *)indexPath
{
    ChildHoodMessage *chmessage = self.messages[indexPath.row];
       if ([self handleVideoWithMessage:chmessage]) {
           NSString *fileId;
           NSString *path;
           if (chmessage.GroupId.length > 3) {
               fileId = chmessage.GroupId;
               if (chmessage.isMine == CHBubbleMessageTypeReceived) {
                   path = [[[ChildHoodService defaultService] groupDownloadVideoPathWithGroupId:fileId] stringByAppendingPathComponent:chmessage.fileName];
               } else {
                   path = [[[ChildHoodService defaultService] groupUploadVideoPathWithGroupId:fileId] stringByAppendingPathComponent:chmessage.fileName];
               }
               
           } else {
               if (chmessage.isMine == CHBubbleMessageTypeReceived) {
                   fileId = chmessage.FriendUserId;
                   path = [[[ChildHoodService defaultService] personalDownloadVideoPathWithUserId:fileId] stringByAppendingPathComponent:chmessage.fileName];
               } else {
                   fileId = chmessage.MineUserId;
                   path = [[[ChildHoodService defaultService] personalUploadVideoPathWithUserId:fileId] stringByAppendingPathComponent:chmessage.fileName];
               }
           }
           

        EFengVideoPlayerViewController *player = [[EFengVideoPlayerViewController alloc]init];
           player.videoFileURL = [NSURL fileURLWithPath:path];
        [player show];
    }
    else
    {
        return;
    }
}
- (void)jumpToDetailInfoViewWithIndexPath:(NSIndexPath *)indexPath
{
    //    if (self.isAPP_Pc) {
    //        return;
    //    }
    ChildHoodMessage *chmessage = self.messages[indexPath.row];
    //app与电脑互联
    if ([chmessage.MineUserId isEqualToString:chmessage.FriendUserId]) {
        return;
    }
    CContactModel *model;
    if (self.group) {
        
        //bug 6064 fixed by 荣则兵
        if (chmessage.isMine == CHBubbleMessageTypeSended) {
            MyInformationVC *info = [[MyInformationVC alloc] init];
            [self.navigationController pushViewController:info animated:YES];
            
        } else {
            model = [[[CContactMgr alloc] init] loadContactWithUserId:chmessage.MineUserId];
            if (model.isDel == 0) {
                if ([model.yuLiuZiduan3 isEqualToString:@"isKefu"]) {
                        
                } else if ([model.yuLiuZiduan3 isEqualToString:@"isWaibu"]){
                    ContactMessageSettingVc *vc = [[ContactMessageSettingVc alloc] init];
                    vc.contact = self.member;
                    [self.navigationController pushViewController:vc animated:YES];
                } else {
                    [MBProgressHUD showError:@"对方已不是组织架构中的成员"];
                }

            } else {
                GroupMemberDetailVC *vc = [[GroupMemberDetailVC alloc] init];
                vc.member = model;
                vc.isFromGroupChat = YES;
                vc.isFromChat = NO;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
        
    } else {
        if (chmessage.isMine == CHBubbleMessageTypeReceived) {
            model = [[[CContactMgr alloc] init] loadContactWithUserId:chmessage.FriendUserId];
//            if (model.isDel == 0 && [model.yuLiuZiduan3 isEqualToString:@""]) {
//                [MBProgressHUD showError:@"该用户已不存在"];
//            } else {
//                if (![model.yuLiuZiduan3 isEqualToString:@"isKefu"]) {
//                    GroupMemberDetailVC *vc = [[GroupMemberDetailVC alloc] init];
//                    vc.member = model;
//                    vc.isFromChat = YES;
//                    vc.isFromGroupChat = NO;
//                    [self.navigationController pushViewController:vc animated:YES];
//                }
//            }
            if (model.isDel == 0) {
                 if ([model.yuLiuZiduan3 isEqualToString:@"isKefu"])
                 {
                     return;
                 }
                 if([model.yuLiuZiduan3 isEqualToString:@"isWaibu"]){
                     GroupMemberDetailVC *vc = [[GroupMemberDetailVC alloc] init];
                     vc.member = model;
                     vc.isFromGroupChat = YES;
                     vc.isFromChat = NO;
                     [self.navigationController pushViewController:vc animated:YES];
                } else {
                    [MBProgressHUD showError:@"对方已不是组织架构中的成员"];
                }
                
            } else {
                GroupMemberDetailVC *vc = [[GroupMemberDetailVC alloc] init];
                vc.member = model;
                vc.isFromGroupChat = YES;
                vc.isFromChat = NO;
                [self.navigationController pushViewController:vc animated:YES];
            }

        } else {
            MyInformationVC *info = [[MyInformationVC alloc] init];
            [self.navigationController pushViewController:info animated:YES];
        }
    }
}
-(void)openredPacketWithIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof (self) weakSelf = self;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在打开...";
    ChildHoodMessage *chMessage = self.messages[indexPath.row];
    CMessageModel *message = [[[CMessageMgr alloc]init] loadMessageByMessageId:chMessage.messageId];
    [[CXmppRequestMgr shareInstance] getRedPacketStatusWithUserId:self.currentUser.UserID AndMessageId:chMessage.messageId successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
        [hud hide:YES];
        if ([responseObject[@"result"] isEqualToString:@"yes"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                robRedPacketViewController *robred = [[robRedPacketViewController alloc]init];
                robred.MessageID = chMessage.messageId;
                [weakSelf.navigationController pushViewController:robred animated:YES];
            });
        }
        else if ([responseObject[@"result"] isEqualToString:@"no"]) {
            if ([responseObject[@"rType"] isEqualToString:@"0"]) {
                //自己发的
                if ([responseObject[@"packetFrom"] isEqualToString:@"1"]) {
                    
                    RedPacketInfo *info = [[RedPacketInfo alloc]init];
                    NSDictionary *dic = [responseObject[@"redPacketInfo"] lastObject];
                    info.userId = dic[@"userId"];
                    info.money = [dic[@"amount"] doubleValue];
                    info.time = dic[@"sendTime"];
                    info.type = PERSON;
                    info.redPacketId = dic[@"redPacketId"];
                    info.userName = dic[@"userName"];
                    info.robed = [dic[@"robStatus"] boolValue];
                    dispatch_async(dispatch_get_main_queue(), ^{
                    selfSendRedPacketViewController *selfsend = [[selfSendRedPacketViewController alloc]init];
                    selfsend.redinfo = info;
                        selfsend.time = message.TimeStamp;
                     [weakSelf.navigationController pushViewController:selfsend animated:YES];
                         });
                }
                else
                {
                    RedPacketInfo *info = [[RedPacketInfo alloc]init];
                    NSDictionary *dic = [responseObject[@"redPacketInfo"] lastObject];
                    info.userId = dic[@"userId"];
                    info.money = [dic[@"amount"] doubleValue];
                    info.time = dic[@"sendTime"];
                    info.type = PERSON;
                    info.redPacketId = dic[@"redPacketId"];
                    info.userName = dic[@"userName"];
                    info.robed = [dic[@"robStatus"] boolValue];
                    dispatch_async(dispatch_get_main_queue(), ^{
                    redPacketResultViewController *result = [[redPacketResultViewController alloc]init];
                        result.message = message;
                    result.redinfo = info;
                    [weakSelf.navigationController pushViewController:result animated:YES];
                });
                }
            }else
            {
               __block redPacketInfoViewController *redInfo = [[redPacketInfoViewController alloc]init];
                NSArray *array = responseObject[@"redPacketInfo"];
                NSMutableArray *infoArray = [NSMutableArray array];
                for (NSDictionary *dic in array) {
                    RedPacketInfo *info = [[RedPacketInfo alloc]init];
                    info.userId = dic[@"userId"];
                    info.money = [dic[@"amount"] doubleValue];
                    info.time = dic[@"sendTime"];
                    info.type = PERSON;
                    info.redPacketId = dic[@"redPacketId"];
                    info.userName = dic[@"userName"];
                    info.robed = [dic[@"robStatus"] boolValue];
                    [infoArray addObject:info];
                }
                redInfo.money = [responseObject[@"redPacket"][@"amount"] doubleValue];
                redInfo.infoArray = [infoArray copy];
                redInfo.message = message;
  
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.navigationController pushViewController:redInfo animated:YES];
            });
            }
        }
        else if([responseObject[@"result"] isEqualToString:@"timeout"])
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                redPacketResultViewController *result = [[redPacketResultViewController alloc]init];
                result.isTimeOut =  YES;
                [weakSelf.navigationController pushViewController:result animated:YES];
            });

        }else if ([responseObject[@"result"] isEqualToString:@"packetover"]){
            dispatch_async(dispatch_get_main_queue(), ^{
                redPacketResultViewController *result = [[redPacketResultViewController alloc]init];
                RedPacketInfo *info = [[RedPacketInfo alloc]init];
                info.money = 0;
                result.redinfo = info;
                result.message = message;
                result.isTimeOut = NO;
                [weakSelf.navigationController pushViewController:result animated:YES];
            });
        } else
        {
            [hud hide:YES];
            [MBProgressHUD showError:@"服务器异常"];
        }
    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [hud hide:YES];
        [MBProgressHUD showError:@"网路错误"];
    }];
    
}
- (void)jumptoDownLoadFileWithIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage *chMessage = self.messages[indexPath.row];
    IMFileDownLoadController *down = [[IMFileDownLoadController alloc] init];
    down.chMessage = chMessage;
    [self.navigationController pushViewController:down animated:YES];
}
-(void)jumptoMapWithIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row < [self.messages count])
    {
    ChildHoodMessage *chMessage = self.messages[indexPath.row];
    ShowMapViewController *map = [[ShowMapViewController alloc]init];
    NSArray *array = [chMessage.fileName componentsSeparatedByString:@","];
    map.location = [[CLLocation alloc]initWithLatitude: [array[1] doubleValue] longitude: [array[2] doubleValue]];
    [self.navigationController pushViewController:map animated:YES];
      }
}

- (void)ShowGroupDetail
{
    //    if (self.isAPP_Pc) {
    //        return;
    //    }
    CGroupModel *group = [self.groupMgr loadGroup:self.group.GroupId];
    if (group.IsDel) {
        //bug 8904 fixed by lixu
        NSString *error = group.groupType == 1 ? @"该讨论组已解散或您已不是该讨论组成员":@"该群已解散或您已不是群成员";
        [MBProgressHUD showError:error];
    } else {
        
        if (self.group.groupType == 1) {
            self.group.yuLiuZiduan2 = 0;
            [self.groupMgr updateGroup:self.group];
            EfengDiscussDetailController *dis = [[EfengDiscussDetailController alloc] init];
            dis.group = self.group;
            [self.navigationController pushViewController:dis animated:YES];
            
        } else {
            self.group.yuLiuZiduan2 = 0;
            self.group.yuLiuZiduan3 = @"noNewNotice";
            [self.groupMgr updateGroup:self.group];
            GroupDetailVC *vc = [[GroupDetailVC alloc] init];
            vc.group = self.group;
            if (_hasNewGroupNotice) {
                vc.isHaveNewNotice = YES;
            }

            [self.navigationController pushViewController:vc animated:YES];
            
        }
    }
    
}

- (void)showMessageSetting
{
    //    if (self.isAPP_Pc) {
    //        return;
    //    }
    CContactModel *model = [[[CContactMgr alloc] init] loadContactWithUserId:self.member.UserID];
    if (model.isDel == 0) {
        if ([model.yuLiuZiduan3 isEqualToString:@"isKefu"]) {
            //bug 9512 fixed by lixu
            ContactMessageSettingVc *vc = [[ContactMessageSettingVc alloc] init];
            vc.contact = self.member;
            [self.navigationController pushViewController:vc animated:YES];

        } else if ([model.yuLiuZiduan3 isEqualToString:@"isWaibu"]){
            ContactMessageSettingVc *vc = [[ContactMessageSettingVc alloc] init];
            vc.contact = self.member;
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            [MBProgressHUD showError:@"对方已不是组织架构中的成员"];
        }
        
    } else {
        ContactMessageSettingVc *vc = [[ContactMessageSettingVc alloc] init];
        vc.contact = self.member;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}
#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMessage) name:K_XMPPRECEIVEMESSAGE object:nil];
    
    //bug 6298 fixed by 荣则兵
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMessageSendStatus:) name:K_XMPPDIDSENDMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMessageSendStatus:) name:K_XMPPFAILEDRECEIVEMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeRedpot:) name:@"REMOVEREDPOT_NOTICE" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeRedPoint:) name:@"removeRedPoint" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mineRefreshMessage) name:@"MineDIdSendMessage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resendMessage:) name:@"RESENDMESSAGE" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePlayVoice:) name:@"chsaudioPlayerPlayVoice" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleMutiViewDownLoadVoice:) name:@"mutiViewDownLoadVoiceStatus" object:nil];
    
    //    删除群聊记录刷新数据 yh
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTable) name:@"DELRECORD" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(savePhone:) name:CBEMOTIONSAVEPHONE object:nil];
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendFile:) name:@"IMFileManagerControllerDidSendFile" object:nil];
    
    CAccountModel *model = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    self.conMgr = [[CContactMgr alloc] init];
    self.presenceMgr = [[CPresenceMgr alloc] init];
    self.currentUser = [self.conMgr loadContactWithUserCode:model.userName];
    self.groupMgr = [[CGroupMgr alloc] init];
    [self.navigationController setNavigationBarHidden:NO];
    //    [self.navigationItem setHidesBackButton:YES];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(back) titleFont:Font18 titleColor:WhiteColor];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"icon-user" title:nil target:self sel:@selector(showMessageSetting) titleFont:Font10 titleColor:WhiteColor];
    self.isShowSection = NO;
    //    /////////////////bug 6065yh
    
    self.messageDraftMgr = [[CMessageDraftMgr alloc] init];
    self.messageMgr = [[CMessageMgr alloc] init];
    NSString *friendId;
    if (self.member) {
        
        if (![self.member.UserID isEqualToString:self.currentUser.UserID]) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePrensence:) name:K_XMPPDIDRECEIVEPRESENCE object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDelUser) name:K_XMPPDELETEUSER object:nil];
        } else {
            self.navigationItem.rightBarButtonItem = nil;
        }
        
        friendId = self.member.UserID;
        self.member.unreadMeassage = [self.messageMgr loadUnReadCountWithMineUserId:self.currentUser.UserID FriendUserId:self.member.UserID];
    } else if (self.group) {
        friendId = self.group.GroupId;
        self.group.unreadMeassage = [self.messageMgr loadGroupUnReadCountWithGroupdId:self.group.GroupId];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatUpdateGroupInfo) name:K_XMPPUPDATEGROUPINFO object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDelGroup) name:K_XMPPDeleteGroup object:nil];
    }
    
    [[ChatToolBar defaultChatToolBar] resetToolPositionToInitial];
    CMessageDraft *messageDraft = [self.messageDraftMgr loadMessageDraftWithFriend:friendId mineId:self.currentUser.UserID];
    ChatToolBar *tool = [ChatToolBar defaultChatToolBar];
    if (messageDraft && messageDraft.MessageContent.length > 0) {
        tool.contentText.text = messageDraft.MessageContent;
        [tool.contentText becomeFirstResponder];
    } else {
        tool.contentText.text = @"";
        [tool.contentText resignFirstResponder];
    }
    
    
    freshView = nil;
    ////////////////////////////
    if (self.member) {
        //    /////////////////bug 6065yh
        if (self.member.unreadMeassage>20) {
            freshView=[[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-110, 26, 110, 15)];
            
            UIImageView *smallImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 4, 11, 7)];
            smallImage.image = [UIImage imageNamed:@"icon-sending.png"];
            smallImage.contentMode = UIViewContentModeCenter;
            smallImage.transform=CGAffineTransformMakeRotation(M_PI_2);
            
            UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(11, 0, 100, 15)];
            lable.font=[UIFont systemFontOfSize:14];
            [lable setTextAlignment:NSTextAlignmentLeft];
            lable.textColor=[UIColor grayColor];
            [freshView addSubview:lable];
            [freshView addSubview:smallImage];
            UIControl *control=[[UIControl alloc]initWithFrame:CGRectMake(0, 0, 110, 15)];
            [control addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
            [freshView addSubview:control];
            
            [self.view addSubview:freshView];
            
            NSString *str=[NSString stringWithFormat:@"%zd条新消息",self.member.unreadMeassage];
            lable.text=str;
            self.firstUnreadMessage = [self.messageMgr loadMinUnReadMessageWithMineUserId:self.currentUser.UserID FriendUserId:self.member.UserID];
        }
        ////////
        
    } else if (self.group) {
        
        //    /////////////////bug 6065yh
        if (self.group.unreadMeassage>20) {
            freshView=[[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-110, 26, 110, 15)];
            
            UIImageView *smallImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 4, 11, 7)];
            smallImage.image = [UIImage imageNamed:@"icon-sending.png"];
            smallImage.contentMode = UIViewContentModeCenter;
            smallImage.transform=CGAffineTransformMakeRotation(M_PI_2);
            
            UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(11, 0, 100, 15)];
            lable.font=[UIFont systemFontOfSize:14];
            [lable setTextAlignment:UITextAlignmentLeft];
            lable.textColor = [UIColor grayColor];
            [freshView addSubview:lable];
            [freshView addSubview:smallImage];
            UIControl *control=[[UIControl alloc]initWithFrame:CGRectMake(0, 0, 110, 26)];
            [control addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
            [freshView addSubview:control];
            
            [self.view addSubview:freshView];
            NSString *str=[NSString stringWithFormat:@"%zd条新消息",self.group.unreadMeassage];
            lable.text=str;
            
            self.firstUnreadMessage = [self.messageMgr loadGroupMinUnReadMessageWithGroupId:self.group.GroupId];
        }
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"icon-naviGroup" title:nil target:self sel:@selector(ShowGroupDetail) titleFont:Font10 titleColor:WhiteColor];
        
        
    } else {
        
    }
    
    //初始化消息数组
    self.messages = [[NSMutableArray alloc] initWithCapacity:1];
    _timestamps = [[NSMutableArray alloc] initWithCapacity:1];
    
    //绑定Delegate
    self.delegate = self;
    self.dataSource = self;
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(doneLoadMoreMessage)];
    [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [header setTitle:@"下拉加载更多" forState:MJRefreshStatePulling];
    [header setTitle:@"加载中 ..." forState:MJRefreshStateRefreshing];
    self.tableView.header = header;
    
    
    _recorder = [[CHSVoiceRecorder alloc] init];
    _hasMsgRefreshNotic = YES;
    _hasNewGroupNotice  = NO;
    [self loadMessage];
    
    
}


#pragma mark 保存联系人号码
- (void)savePhone:(NSNotification *)notice
{
    NSString *phone = notice.userInfo[@"phone"];
    
    CFTypeRef phoneRef = (__bridge CFTypeRef)phone;
    
    ABUnknownPersonViewController *new=[[ABUnknownPersonViewController alloc]init];
    new.unknownPersonViewDelegate = self;
    
    ABRecordRef record = ABPersonCreate();
    CFErrorRef error;
    //    // 设置联系人的名字
    //    ABRecordSetValue(record, kABPersonFirstNameProperty, (__bridge CFTypeRef)[NSString stringWithFormat:@"%@",@"haode"], &error);
    // 添加联系人电话号码以及该号码对应的标签名
    ABMultiValueIdentifier idOut = kABMultiValueInvalidIdentifier;
    ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(multi, phoneRef, kABPersonPhoneMobileLabel, &idOut);
    ABRecordSetValue(record, kABPersonPhoneProperty, multi, &error);
    
    ABAddressBookRef addressBook = nil;
    // 如果为iOS6以上系统，需要等待用户确认是否允许访问通讯录。
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
    {
        addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        //等待同意后向下执行
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)                                                 {
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }else{
        addressBook = ABAddressBookCreate();
    }
    // 将新建联系人记录添加如通讯录中
    
    
    new.displayedPerson = record;
    new.allowsAddingToAddressBook = YES;//允许添加
    new.addressBook = addressBook;
    //    new.allowsActions = YES;//默认no，设置为yes可以显示发送消息以及打电话
    
    
    CFRelease(addressBook);
    CFRelease(record);
    CFRelease(multi);
    [self.navigationController pushViewController:new animated:YES];
    
}

- (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController didResolveToPerson:(nullable ABRecordRef)person
{
    
}

// Called when the user selects an individual value in the unknown person view, identifier will be kABMultiValueInvalidIdentifier if a single value property was selected.
// Return NO if you do not want anything to be done or if you are handling the actions yourself.
// Return YES if you want the ABUnknownPersonViewController to perform its default action.
- (BOOL)unknownPersonViewController:(ABUnknownPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    
    return YES;
}

#pragma mark chatool 文本改变代理
- (void)contentTextViewTextDidChangeWithText:(NSString *)text
{
    if (![self.conMgr isAvalableContactWithUserId:self.currentUser.UserID]) {
        return;
    }
    if (self.group) {
        if ([self.groupMgr isAvalableGroupWithGroupId:self.group.GroupId]) {
            
        } else {
            return;
        }
    } else {
        if ([self.conMgr isAvalableContactWithUserId:self.member.UserID]) {
            
        } else {
            return;
        }
    }
    
    
    NSString *contentText = [ChatToolBar defaultChatToolBar].contentText.text;
    
    NSString *friendId;
    if (self.group) {
        friendId = self.group.GroupId;
    } else if (self.member) {
        friendId = self.member.UserID;
    }
    if (contentText.length > 0) {
        
        CMessageDraft *messageDraft = [self.messageDraftMgr loadMessageDraftWithFriend:friendId mineId:self.currentUser.UserID];
        if (messageDraft) {
            if ([messageDraft.MessageContent isEqualToString:contentText]) {
                
            } else {
                messageDraft.MineUserId = self.currentUser.UserID;
                messageDraft.MessageContent = [ChatToolBar defaultChatToolBar].contentText.text;
                messageDraft.TimeStamp = [UIUtil getCurrentTimeStamp];
                messageDraft.MessageSendedStatus = kMessageUserMute;
                messageDraft.MineUserName = self.currentUser.UserName;
                if (self.group) {
                    messageDraft.FriendUserId = self.group.GroupId;
                    messageDraft.FriendUserName = self.group.GroupName;
                    messageDraft.GroupId = self.group.GroupId;
                    messageDraft.yuLiuZiduan2 = self.group.groupType;
                } else if (self.member) {
                    messageDraft.FriendUserId = self.member.UserID;
                    messageDraft.FriendUserName = self.member.UserName;
                }
                messageDraft.IsShowInmessageList = YES;
                messageDraft.MessageType = @"text";
                [self.messageDraftMgr updateMessageDraftWithMessageDraft:messageDraft];
                //                [mgr delMessageDraftWithFriend:messageDraft.FriendUserId mineId:self.currentUser.UserID];
                //                [mgr insertMessageDraft:messageDraft];
                
            }
        } else {
            messageDraft = [[CMessageDraft alloc] init];
            messageDraft.MineUserId = self.currentUser.UserID;
            messageDraft.MessageContent = [ChatToolBar defaultChatToolBar].contentText.text;
            messageDraft.TimeStamp = [UIUtil getCurrentTimeStamp];
            messageDraft.MessageSendedStatus = kMessageUserMute;
            messageDraft.MineUserName = self.currentUser.UserName;
            if (self.group) {
                messageDraft.FriendUserId = self.group.GroupId;
                messageDraft.FriendUserName = self.group.GroupName;
                messageDraft.GroupId = self.group.GroupId;
                messageDraft.yuLiuZiduan2 = self.group.groupType;
            } else if (self.member) {
                messageDraft.FriendUserId = self.member.UserID;
                messageDraft.FriendUserName = self.member.UserName;
            }
            messageDraft.IsShowInmessageList = YES;
            messageDraft.MessageType = @"text";
            [self.messageDraftMgr delMessageDraftWithFriend:messageDraft.FriendUserId mineId:self.currentUser.UserID];
            [self.messageDraftMgr insertMessageDraft:messageDraft];
            
        }
    } else {
        [self.messageDraftMgr delMessageDraftWithFriend:friendId mineId:self.currentUser.UserID];
    }
    
    
}

- (void)handleDelUser{
    
}

- (void)handleDelGroup
{
    
}
//fixbug 8527 by Lixu
-(void)setNaviagationTitle
{
    self.group = [[[CGroupMgr alloc] init] loadGroup:self.group.GroupId];
    if (self.group) {
        if ([self.group.yuLiuZiduan3 isEqualToString:@"haveNewNotice"]) {
            _hasNewGroupNotice = YES;
        }
        else
        {
            _hasNewGroupNotice = NO;
        }
            UIButton *btn = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
            if (self.group.yuLiuZiduan2||_hasNewGroupNotice) {
                
                [btn setImage:[UIImage imageNamed:@"btn_qunziliao"] forState:UIControlStateNormal];
                [btn setImage:[UIImage imageNamed:@"btn_qunziliao"] forState:UIControlStateSelected];
                [btn setImage:[UIImage imageNamed:@"btn_qunziliao"] forState:UIControlStateHighlighted];
                
            } else {
                
                [btn setImage:[UIImage imageNamed:@"icon-naviGroup"] forState:UIControlStateNormal];
                [btn setImage:[UIImage imageNamed:@"icon-naviGroup"] forState:UIControlStateSelected];
                [btn setImage:[UIImage imageNamed:@"icon-naviGroup"] forState:UIControlStateHighlighted];
            }
    
        if (self.group.groupType == 1) {
            BOOL type;
            if (self.group.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND || self.group.messageSettingType == MESSAGESETTING_ONLYSHOWUNREADCOUNT) {
                type = YES;
            }
            else
            {
                type = NO;
            }
            NSString *nameStr = [self.group.GroupName stringByReplacingOccurrencesOfString:@"," withString:@"、"];
            
            [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@(%zd)",[nameStr stringByReplacingOccurrencesOfString:@"，" withString:@"、"],self.group.UserNum] andMessageSettingType:type];
        } else {
            BOOL type;
            if (self.group.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND || self.group.messageSettingType == MESSAGESETTING_ONLYSHOWUNREADCOUNT) {
                type = YES;
            }
            else
            {
                type = NO;
            }
            [self.navigationItem setNewTitleCenter:self.group.GroupName andMessageSettingType:type];
        }
    }
    if (self.member) {
        if (![self.member.UserID isEqualToString:self.currentUser.UserID]) {
            CPresenceModel *presence = [self.presenceMgr getPresenceWithUserCode:self.member.UserCode];
            NSString *availableStr;
            if (presence) {
                if ([presence.IsAvailable isEqualToString:@"在线"] || [presence.pcAvailable isEqualToString:@"在线"]) {
                    availableStr = @"在线";
                } else {
                    availableStr = @"离线";
                }
                
            } else {
                availableStr = @"离线";
            }
            BOOL type;
            if (self.member.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND || self.member.messageSettingType == MESSAGESETTING_ONLYSHOWUNREADCOUNT) {
                type = YES;
            }
            else
            {
                type = NO;
            }
            //bug 8843 8848 9562fixed by lixu
            NSRange range = [self.currentUser.UserCode rangeOfString:@"wanzhao.com"];
            if (([self.member.yuLiuZiduan3 isEqualToString:@"isKefu"] || [self.member.yuLiuZiduan3 isEqualToString:@"isWaibu"])&& range.location == NSNotFound) {
                availableStr = @"在线";
            }
            [self.navigationItem setNewAttributeTitleCenter:self.member.UserName str2:availableStr andMessageSettingType:type];
            
            
            
        } else {
            [self.navigationItem setNewTitleCenter:@"我的电脑"];
        }
    }
}
- (void)chatUpdateGroupInfo
{
    [self setNaviagationTitle];
    //    [self.navigationItem setNewTitleCenter:self.group.GroupName];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}
- (void)click{
    [freshView removeFromSuperview];
    freshView = nil;
    if (self.member) {
        [self refresh:self.member.unreadMeassage];
    }else if (self.group){
        [self refresh:self.group.unreadMeassage];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (freshView) {
        for(ChildHoodMessage *message in self.messages)
        {
            if([message.messageId isEqualToString:self.firstUnreadMessage.MessageId])
            {
                [freshView removeFromSuperview];
                freshView = nil;
            }
            
        }
        
    }
    
}


//重发消息
#pragma mark 重发消息
- (void)resendMessage:(NSNotification *)notice
{
            __block NSIndexPath *rsendIndexPath = nil;
            ChildHoodMessage *childMessage = notice.object;
            
            [self.messageMgr delMessageWithMessageId:childMessage.messageId];
            [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *obj, NSUInteger idx, BOOL *stop) {
                if ([obj.messageId isEqualToString:childMessage.messageId]) {
                    [self.messages removeObject:obj];
                    rsendIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                    *stop = YES;
                }
            }];
            if (childMessage.messageType == SNSPMaterialTypeKMessage) {
                [[CXmppRequestMgr shareInstance] sendMessageWithMessage:childMessage.messageContent messageId:childMessage.messageId curUser:self.currentUser member:self.member group:self.group];
            } else if (childMessage.messageType == SNSPMaterialTypeKAudio) {
                
                [[CXmppRequestMgr shareInstance] sendVoiceMessageWihtCurUser:self.currentUser messageId:childMessage.messageId member:self.member group:self.group fileName:childMessage.fileName timeLenth:childMessage.SoundLenth];
            } else if (childMessage.messageType == SNSPMaterialTypeKImage) {
                NSString *imgDataStr = nil;
                if (self.group) {
                    imgDataStr =  [[[ChildHoodService defaultService] groupUploadImagePathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:childMessage.fileName];
                } else {
                    imgDataStr = [[[ChildHoodService defaultService] personalUploadImagePathWithUserId:self.currentUser.UserID] stringByAppendingPathComponent:childMessage.fileName];
                }
                
                [[CXmppRequestMgr shareInstance] sendImageMessage:[UIImage imageWithContentsOfFile:imgDataStr] messageId:childMessage.messageId index:0 curUser:self.currentUser member:self.member group:self.group fileName:childMessage.fileName];
            } else if (childMessage.messageType == SNSPMaterialTypeKVideo){
                NSString *imgDataStr = nil;
                if (self.group) {
                    imgDataStr =  [[[ChildHoodService defaultService] groupUploadVideoPathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:childMessage.fileName];
                } else {
                    imgDataStr = [[[ChildHoodService defaultService] personalUploadVideoPathWithUserId:self.currentUser.UserID] stringByAppendingPathComponent:childMessage.fileName];
                }
                NSURL *url = [NSURL fileURLWithPath:imgDataStr];
                UIImage *videoImage = [self thumbnailImageForVideo:url atTime:0];
                NSData *videoData = [NSData dataWithContentsOfURL:url];
                [[CXmppRequestMgr shareInstance] sendVideoMessage:videoData videoImage:videoImage messageId:childMessage.messageId curUser:self.currentUser member:self.member group:self.group fileName:childMessage.fileName];

            }else if (childMessage.messageType == SNSPMaterialTypeKFile) {
                CFileModel *fileModel = [[CFileModel alloc] init];
                NSString *fileId;
                NSString *fileName;
                
                if (childMessage.GroupId.length > 3) {
                    fileId = childMessage.GroupId;
                    fileName = [UIUtil getGroupFileNameWithServerFileName:childMessage.fileName];
                    
                } else {
                    fileName = [UIUtil getFileNameWithServerFileName:childMessage.fileName];
                    fileId = childMessage.MineUserId;
                }
                fileModel.FileName = fileName;
                fileModel.serverFileName = childMessage.fileName;
                NSString *localFilePath = nil;
                if (self.group) {
                    localFilePath = [[[ChildHoodService defaultService] groupUpLoadFilePathWithGroupId:fileId] stringByAppendingPathComponent:childMessage.fileName];
                } else {
                    localFilePath = [[[ChildHoodService defaultService] personalUpLoadFilePathWithUserId:fileId] stringByAppendingPathComponent:childMessage.fileName];
                }
                
                if ([NSData dataWithContentsOfFile:localFilePath].length == childMessage.fileLenth.longLongValue) {
                    fileModel.LocalFilePath = localFilePath;
                } else {
                    [MBProgressHUD showError:@"文件不存在或文件已被损坏！"];
                    return;
                }
                [[CXmppRequestMgr shareInstance] sendFile:fileModel messageId:childMessage.messageId curUser:self.currentUser member:self.member group:self.group];
            } else {
                
            }
}
- (void)refreshTable
{
    [self loadMessage];
    [self.tableView reloadData];
}

-(void)refresh:(NSInteger)num{
    
        NSArray *array;
        if (self.member) {
            
            array = [self.messageMgr loadUnReadMessageWithMineUserId:self.currentUser.UserID FriendUserId:self.member.UserID beginTimeStamp:self.firstUnreadMessage.TimeStamp endTimeStamp:self.minMessage.TimeStamp];
            
            
        } else if (self.group) {
            
            array = [self.messageMgr loadGroupUnReadMessageWithGroupdId:self.group.GroupId beginTimeStamp:self.firstUnreadMessage.TimeStamp endTimeStamp:self.minMessage.TimeStamp];
            
        }
        
        CMessageModel *last = array.lastObject;
        self.minMessage = last;
        
        NSMutableArray *arryMore = [NSMutableArray arrayWithCapacity:array.count];
        [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
            
            [arryMore addObject:[self handleChildHoodMessageWithMessage:obj]];
        }];
        
        NSMutableArray *arrayM = [NSMutableArray array];
        [arrayM addObjectsFromArray:arryMore];
        [arrayM addObjectsFromArray:self.messages];
        self.messages = arrayM;
        
        if (self.messages.count > 0) {
            self.messages = [[self.messages sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"messageTime" ascending:YES]]] mutableCopy];
        }
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom
                                      animated:YES];
}

//bug 6347 fixed by 荣则兵

- (void)handlePrensence:(NSNotification *)notice
{
    [self setNaviagationTitle];
}

//chimageScanView 代理
-(void)removeRedPoint:(NSNotification *)notice
{
    __block NSIndexPath *redIndexPath = nil;
    __block NSString *messageId = notice.object;
    [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *obj, NSUInteger idx, BOOL *stop) {
        if ([obj.messageId isEqualToString:messageId]) {
            obj.isPlayed = MessageSoundPlayed;
            redIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
            *stop = YES;
        }
    }];
    
    if (redIndexPath == nil) {
        return;
    }
    [self.tableView reloadRowsAtIndexPaths:@[redIndexPath] withRowAnimation:UITableViewRowAnimationNone];

}
- (void)removeRedpot:(NSNotification *)notice
{
            __block NSIndexPath *redIndexPath = nil;
            __block ChildHoodMessage *childMessage = notice.object;
            CMessageModel *model = [self.messageMgr loadMessageByMessageId:childMessage.messageId];
    if (model.SoundPlayStatus != MessageSoundPlayed) {
        NSString *messageID = [NSString string];
        NSRange range = [childMessage.messageId rangeOfString:@"-"];
        if (range.location != NSNotFound) {
            messageID = [childMessage.messageId substringToIndex:range.location];
        }
        else
        {
            messageID = childMessage.messageId;
        }
        [[CXmppRequestMgr shareInstance] updateMessageReadStatusWithMessageIds:messageID messageType:@"sound"];

            model.SoundPlayStatus = childMessage.isPlayed;
            [self.messageMgr updateMessage:model];
            
            [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *obj, NSUInteger idx, BOOL *stop) {
                
                if ([obj.messageId isEqualToString:childMessage.messageId]) {
                    obj.isPlayed = childMessage.isPlayed;
                    redIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                    *stop = YES;
                }
            }];
            
            if (redIndexPath == nil) {
                return;
            }
            [self.tableView reloadRowsAtIndexPaths:@[redIndexPath] withRowAnimation:UITableViewRowAnimationNone];
 }
}
- (void)handlePlayVoice:(NSNotification *)notice
{
            __block NSIndexPath *redIndexPath = nil;
            __block ChildHoodMessage *childMessage = notice.object;
            CMessageModel *model = [self.messageMgr loadMessageByMessageId:childMessage.messageId];
    model.SoundPlayStatus = childMessage.isPlayed;
            [self.messageMgr updateMessage:model];
            [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *obj, NSUInteger idx, BOOL *stop) {
                
                if ([obj.messageId isEqualToString:childMessage.messageId]) {
                    obj.isPlayed = childMessage.isPlayed;
                    redIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                    *stop = YES;
                }
            }];
            if (redIndexPath == nil) {
                return;
            }
            [self.tableView reloadRowsAtIndexPaths:@[redIndexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)handleMutiViewDownLoadVoice:(NSNotification *)notice
{
            __block NSIndexPath *redIndexPath = nil;
            __block ChildHoodMessage *childMessage = notice.object;
            
            CMessageModel *model = [self.messageMgr loadMessageByMessageId:childMessage.messageId];
            model.MessageSendedStatus = childMessage.messageStatus;
            [self.messageMgr updateMessage:model];
            
            [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *obj, NSUInteger idx, BOOL *stop) {
                
                if ([obj.messageId isEqualToString:childMessage.messageId]) {
                    obj.isPlayed = childMessage.isPlayed;
                    redIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                    *stop = YES;
                }
            }];
            
            if (redIndexPath == nil) {
                return;
            }
            [self.tableView reloadRowsAtIndexPaths:@[redIndexPath] withRowAnimation:UITableViewRowAnimationNone];
            
}

//bug 6298 fixed by 荣则兵
- (void)updateMessageSendStatus:(NSNotification *)notice
{
        NSString *mesId = notice.object;
        CMessageModel *model = [self.messageMgr loadMessageWithMessageId:mesId];
         __block NSIndexPath *indexPath;
        
        if ([model.FriendUserId isEqualToString:self.member.UserID] || (model.GroupId != nil && [model.GroupId isEqualToString:self.group.GroupId])) {
           
            [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *message, NSUInteger idx, BOOL *stop) {
                
                if ([message.messageId isEqualToString:model.MessageId]) {
                    message.messageStatus = model.MessageSendedStatus;
                    indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                    *stop = YES;
                }
            }];
                   }

        
            if (indexPath == nil) {
                return;
            }

       [self.tableView reloadData];
    }
-(void)updateMemory:(NSNotification *)noti
{
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setNaviagationTitle];
    if (IsIOS7) {
        [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(44, 170, 253)];
    } else {
        [self.navigationController.navigationBar setTintColor:RGBCOLOR(44, 170, 253)];
    }
    
    
    if (self.group) {
        
        UIButton *btn = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
        if (self.group.yuLiuZiduan2) {
            [btn setImage:[UIImage imageNamed:@"btn_qunziliao"] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"btn_qunziliao"] forState:UIControlStateSelected];
            [btn setImage:[UIImage imageNamed:@"btn_qunziliao"] forState:UIControlStateHighlighted];
            
        } else {
            [btn setImage:[UIImage imageNamed:@"icon-naviGroup"] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"icon-naviGroup"] forState:UIControlStateSelected];
            [btn setImage:[UIImage imageNamed:@"icon-naviGroup"] forState:UIControlStateHighlighted];
        }
    }
    
    if (self.member && [self.member.UserID isEqualToString:self.currentUser.UserID]) {
        
        [[ChatToolBar defaultChatToolBar] setPC_APPChatFrame];
        [ChatToolMoreView defaultMoreView].duanxin.hidden = YES;
        [ChatToolMoreView defaultMoreView].message.hidden = YES;
        //        [ChatToolMoreView defaultMoreView].scrollView.contentSize = CGSizeMake(0, 0);
        //        [ChatToolMoreView defaultMoreView].pageControl.hidden = YES;
    }  else {
        [[ChatToolBar defaultChatToolBar] setNormalChatFrame];
        [ChatToolMoreView defaultMoreView].duanxin.hidden = NO;
        [ChatToolMoreView defaultMoreView].message.hidden = NO;
        //        [ChatToolMoreView defaultMoreView].scrollView.contentSize = CGSizeMake(2 * HARDWARE_SCREEN_WIDTH, 0);
        //        [ChatToolMoreView defaultMoreView].pageControl.hidden = NO;
    }
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}



- (void)refreshMessage
{
         BOOL isScroll = [self isNeedScrollToBottom];
        NSArray *array;
        if (self.member) {
            array = [self.messageMgr loadMessageWithMineId:self.currentUser.UserID FrinendId:self.member.UserID TimeStamp:self.maxMessage.TimeStamp];
            
            [self updateMessageReadStatusToServiceWithArray:array];
            
            [self.messageMgr updateMessageReadStatusWithMineUserId:self.currentUser.UserID FriendUserId:self.member.UserID Status:YES];
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TabBadgeChangeValue" object:nil];
        } else {
            array = [self.messageMgr loadGroupMessageWithGroupId:self.group.GroupId TimeStamp:self.maxMessage.TimeStamp];
            
            [self updateMessageReadStatusToServiceWithArray:array];
            
            [self.messageMgr updateGroupMessageReadStatusWithGroupId:self.group.GroupId Status:YES];
            
            
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TabBadgeChangeValue" object:nil];
            
        }
        if (array.count > 0) {
            CMessageModel *last = array.lastObject;
            self.maxMessage = last;
            for (CMessageModel *obj in array) {
                
                [self.messages addObject:[self handleChildHoodMessageWithMessage:obj]];
                
            }
            
            if (self.messages.count > 0) {
                self.messages = [[self.messages sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"messageTime" ascending:YES]]] mutableCopy];
                
                   [self.tableView reloadData];
                   if (isScroll) {
                       [self scrollToBottomAnimated:NO];
                       return;
                   }

            }
            
        }

}


- (void)mineRefreshMessage
{
        NSArray *array;
        if (self.member) {
            
            array = [self.messageMgr loadMessageWithMineId:self.currentUser.UserID FrinendId:self.member.UserID TimeStamp:self.maxMessage.TimeStamp];
            
            //        [[[CMessageMgr alloc] init] updateMessageReadStatusWithMineUserId:self.currentUser.UserID FriendUserId:self.member.UserID Status:YES];
            //
            //        [self updateMessageReadStatusToServiceWithArray:array];
            
            //        [[NSNotificationCenter defaultCenter] postNotificationName:@"TabBadgeChangeValue" object:nil];
        } else {
            array = [self.messageMgr loadGroupMessageWithGroupId:self.group.GroupId TimeStamp:self.maxMessage.TimeStamp];
            
            //        [[[CMessageMgr alloc] init] updateGroupMessageReadStatusWithGroupId:self.group.GroupId Status:YES];
            //
            //
            //
            //        [self updateMessageReadStatusToServiceWithArray:array];
            //
            //        [[NSNotificationCenter defaultCenter] postNotificationName:@"TabBadgeChangeValue" object:nil];
            //
        }
        if (array.count > 0) {
            CMessageModel *last = array.lastObject;
            self.maxMessage = last;
            for (CMessageModel *obj in array) {
                
                [self.messages addObject:[self handleChildHoodMessageWithMessage:obj]];
                
            }
            
            self.messages = [[self.messages sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"messageTime" ascending:YES]]] mutableCopy];
            if (self.messages.count > 0) {
                
                    [self.tableView reloadData];
                    [self scrollToBottomAnimated:YES];
            }
            
        }
        
}

//向服务器发送消息的已读状态
- (void)updateMessageReadStatusToServiceWithArray:(NSArray *)array
{
    NSString *messageIds = [NSString string];
    for (CMessageModel *mesModel in array) {
        if (!mesModel.isMineSend) {
            NSRange range = [mesModel.MessageId rangeOfString:@"-"];
            if (range.location != NSNotFound) {
                NSString *str = [mesModel.MessageId substringToIndex:range.location];
                messageIds = [messageIds stringByAppendingFormat:@"%@,",str];
            }
            else
            {
                messageIds = [messageIds stringByAppendingFormat:@"%@,",mesModel.MessageId];
            }
            
        }
        if (messageIds.length>5) {
            messageIds = [messageIds substringToIndex:messageIds.length - 1];
            [[CXmppRequestMgr shareInstance] updateMessageReadStatusWithMessageIds:messageIds messageType:@"message"];
        }
    }
    

}

- (void)loadMessage
{
        [self.messages removeAllObjects];
        NSArray *array;
        if (self.member) {
            array = [self.messageMgr loadMessageWithMineId:self.currentUser.UserID FrinendId:self.member.UserID Page:@"0" PerPage:@"20"];
            
            
            [self updateMessageReadStatusToServiceWithArray:[self.messageMgr loadAllUnReadMessageWithMineUserId:self.currentUser.UserID FriendUserId:self.member.UserID]];
            
            [self.messageMgr updateMessageReadStatusWithMineUserId:self.currentUser.UserID FriendUserId:self.member.UserID Status:YES];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TabBadgeChangeValue" object:nil];
        } else if (self.group) {
            array = [self.messageMgr loadGroupMessageWithGroupId:self.group.GroupId Page:@"0" PerPage:@"20"];
            
            [self updateMessageReadStatusToServiceWithArray:[self.messageMgr loadAllUnReadMessageWithGroupdId:self.group.GroupId]];
            
            [self.messageMgr updateGroupMessageReadStatusWithGroupId:self.group.GroupId Status:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TabBadgeChangeValue" object:nil];
        }
        self.maxMessage = array.firstObject;
        self.minMessage = array.lastObject;
        //    [self.messages addObjectsFromArray:_resultControl.fetchedObjects];
        
        [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
            
            [self.messages addObject:[self handleChildHoodMessageWithMessage:obj]];
        }];
        
        self.messages = [[self.messages sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"messageTime" ascending:YES]]] mutableCopy];
        if (self.messages.count > 0) {
           
                
                [self.tableView reloadData];
                [self scrollToBottomAnimated:NO];
           
        }
    
}

- (void)doneLoadMoreMessage
{
    //    _reloading = NO;
    
    
    
        NSArray *array;
        if (self.member) {
            array = [self.messageMgr loadMoreHistoryMessageWithMineId:self.currentUser.UserID FrinendId:self.member.UserID Page:@"0" PerPage:@"20" TimeStamp:self.minMessage.TimeStamp];
            
        } else {
            
            array = [self.messageMgr loadMoreGroupHistoryMessageWithGroupId:self.group.GroupId Page:@"0" PerPage:@"20" TimeStamp:self.minMessage.TimeStamp];
        }
        
        if (array.count > 0) {
            self.isShowSection = NO;
            NSMutableArray *arryMore = [NSMutableArray arrayWithCapacity:array.count];
            CMessageModel *last = array.lastObject;
            self.minMessage = last;
            [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
                [arryMore addObject:[self handleChildHoodMessageWithMessage:obj]];
            }];
            
            
            NSMutableArray *arrayM = [NSMutableArray array];
            [arrayM addObjectsFromArray:arryMore];
            [arrayM addObjectsFromArray:self.messages];
            self.messages = arrayM;
            if (self.messages.count>0) {
                self.messages = [[self.messages sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"messageTime" ascending:YES]]] mutableCopy];
                
            }
            
        } else {
            self.isShowSection = YES;
        }
       
            [self.tableView.header endRefreshing];
            
            [self.tableView reloadData];
        
}

- (ChildHoodMessage *)handleChildHoodMessageWithMessage:(CMessageModel *)obj
{
    SNSPMessage* snspMessage  = nil;
    //        NSString* strFile = [NSString stringWithFormat:@"message_%lld.data", messageModel.messageIndex];
    //        snspMessage = [CHMessageManager loadSNSPMessage:strFile];
    if(snspMessage == nil)
    {
        
        SNSPMessage_Builder* messageBuilder = [[SNSPMessage builder] clear];
        
        
        
        [messageBuilder setContent:[obj.MessageContent dataUsingEncoding:NSUTF8StringEncoding]];
        //            [messageBuilder setMemoryId:[messageModel.memoryId intValue]];
        //            [messageBuilder setRoomId:[messageModel.roomId longLongValue]];
        //            [messageBuilder setRelativeType:[messageModel.relativeType intValue]];
        if (self.group) {
            if (obj.isMineSend == YES) {
                [messageBuilder addAttachmentFileKeys:[[[ChildHoodService defaultService] groupUploadImagePathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:obj.FileName]];
                
            } else {
                [messageBuilder addAttachmentFileKeys:[[[ChildHoodService defaultService] groupDownloadImagePathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:obj.FileName]];
            }
            
        } else {
            
            if (obj.isMineSend == YES) {
                [messageBuilder addAttachmentFileKeys:[[[ChildHoodService defaultService] personalUploadImagePathWithUserId:self.currentUser.UserID] stringByAppendingPathComponent:obj.FileName]];
            } else {
                [messageBuilder addAttachmentFileKeys:[[[ChildHoodService defaultService] groupDownloadImagePathWithGroupId:self.member.UserID] stringByAppendingPathComponent:obj.FileName]];
            }
        }
        
        int64_t tt = obj.TimeStamp.longLongValue;//[[UIUtil antiGetSystemTime:messageModel.messageTime] timeIntervalSince1970]*1000;
        [messageBuilder setCreateTime:tt];
        if ([obj.MessageType isEqualToString:@"text"]) {
            [messageBuilder setMaterialType:SNSPMaterialTypeKMessage];
        } else if ([obj.MessageType isEqualToString:@"voice"]) {
            [messageBuilder setMaterialType:SNSPMaterialTypeKAudio];
        } else if ([obj.MessageType isEqualToString:@"image"]) {
            [messageBuilder setMaterialType:SNSPMaterialTypeKImage];
        } else if ([obj.MessageType isEqual:@"file"]){
            [messageBuilder setMaterialType:SNSPMaterialTypeKFile];
        } else if ([obj.MessageType isEqualToString:@"shke"]){
             [messageBuilder setMaterialType:SNSPShake];
        } else if ([obj.MessageType isEqual:@"video"]){
            [messageBuilder setMaterialType:SNSPMaterialTypeKVideo];
        } else if ([obj.MessageType isEqualToString:@"redpacket"]){
            [messageBuilder setMaterialType:SNSRedPacket];
        }
        
        [messageBuilder setMessageType:SNSPMessageTypeKMessageType];
        [messageBuilder setMessageId:2222222];
        snspMessage = [messageBuilder build];
        
    }
    ChildHoodMessage* chmessage = [[ChildHoodMessage alloc]initWithSNSMessage:snspMessage];
    chmessage.messageStatus = obj.MessageSendedStatus;
    chmessage.SoundLenth = obj.MessageContent.integerValue;
    chmessage.messageDBID = obj.MessageIndex;
    chmessage.isPlayed = obj.SoundPlayStatus;
    chmessage.fileName = obj.FileName;
    chmessage.messageId = obj.MessageId;
    chmessage.companyCode = obj.yuLiuZiduan1;
    if (self.group) {
        if (obj.isMineSend) {
            
        } else {
            chmessage.fromName = [self.conMgr loadContactNameWithUserId:obj.MineUserId];
        }
    }
    //        chmessage.totalCount = messageModel.totalCount;
    //
    //        chmessage.messageDBID = messageModel.messageIndex;
    if ([obj.MessageType isEqualToString:@"text"]||[obj.MessageType isEqualToString:@"shke"]) {
        
        
    } else if ([obj.MessageType isEqualToString:@"voice"]) {
        if (self.group) {
            if (obj.isMineSend) {
                chmessage.fileUri = [[[ChildHoodService defaultService] groupUploadSoundPathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:obj.FileName];
            } else {
                chmessage.fileUri = [[[ChildHoodService defaultService] groupDownloadSoundPathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:obj.FileName];
            }
        } else {
            if (obj.isMineSend) {
                chmessage.fileUri = [[[ChildHoodService defaultService] personalUploadSoundPathWithUserId:self.currentUser.UserID] stringByAppendingPathComponent:obj.FileName];
                
            } else {
                chmessage.fileUri = [[[ChildHoodService defaultService] personalDownloadSoundPathWithUserId:self.member.UserID] stringByAppendingPathComponent:obj.FileName];
            }
            
        }
    } else if ([obj.MessageType isEqualToString:@"image"]||[obj.MessageType isEqualToString:@"video"]) {
        chmessage.fileUri = obj.Stream;
    }
    
    if (obj.isMineSend) {
        chmessage.isMine = CHBubbleMessageTypeSended;
        //            chmessage.fileUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:self.currentUser.UserID];
    } else {
        chmessage.isMine = CHBubbleMessageTypeReceived;
        
    }
    chmessage.GroupId = obj.GroupId;
    chmessage.MineUserId = obj.MineUserId;
    chmessage.FriendUserId = obj.FriendUserId;
    if ([self.conMgr isKefuContactWithUserId:obj.FriendUserId]) {
        chmessage.isKefu = YES;
    } else {
        chmessage.isKefu = NO;
    }
    chmessage.fileLenth = obj.FileSize;
    return chmessage;
}


- (void)sendTextMessage:(NSString *)message
{
    NSInteger index = 0;
    if([UIApplication sharedApplication].windows.count > 1)index=1;
    UIWindow *win=[[UIApplication sharedApplication].windows objectAtIndex:index];
    //    如果消息为空，则不发送,提示用户
    if ([self checkTextCount:message] <= 0) {
        MBProgressHUD *progress = [[MBProgressHUD alloc] initWithView:win];
        progress.removeFromSuperViewOnHide = YES;
        [progress setMode:MBProgressHUDModeText];
        progress.labelText = @"内容不能为空";
        [win addSubview:progress];
        [win bringSubviewToFront:progress];
        [progress show:YES];
        [progress hide:YES afterDelay:1.0f];
        return;
    }
    
    
    NSString *friendId;
    if (self.group) {
        friendId = self.group.GroupId;
    } else if (self.member) {
        friendId = self.member.UserID;
    }
    [self.messageDraftMgr delMessageDraftWithFriend:friendId mineId:self.currentUser.UserID];
    
    if (![self.conMgr isAvalableContactWithUserId:self.currentUser.UserID]) {
        [MBProgressHUD showError:@"您已不是组织架构中的成员"];
        return;
    }
    
    if (self.group) {
        if ([self.groupMgr isAvalableGroupWithGroupId:self.group.GroupId]) {
            
        } else {
            NSString *error = self.group.groupType == 1 ? @"您已不是该讨论组成员":@"您已不是该群成员";
            [MBProgressHUD showError:error];
            return;
        }
    } else {
        if ([self.conMgr isAvalableContactWithUserId:self.member.UserID]) {
            
        } else {
            [MBProgressHUD showError:@"对方已不是组织架构中的成员"];
            return;
        }
    }
    [[CXmppRequestMgr shareInstance] sendMessageWithMessage:message messageId:nil curUser:self.currentUser member:self.member group:self.group];
    self.sendType = SNSPMaterialTypeKMessage;
    self.messageContent = message;
    
}
-(void)sendVideoMessage:(NSURL*)url
{
    
    if (![self.conMgr isAvalableContactWithUserId:self.currentUser.UserID]) {
        [MBProgressHUD showError:@"您已不是组织架构中的成员"];
        return;
    }
    
    
    if (self.group) {
        if ([self.groupMgr isAvalableGroupWithGroupId:self.group.GroupId]) {
            
        } else {
            NSString *error = self.group.groupType == 1 ? @"该讨论组已解散或您已不是该讨论组成员":@"该群已解散或您已不是群成员";
            [MBProgressHUD showError:error];
            return;
        }
    } else {
        if ([self.conMgr isAvalableContactWithUserId:self.member.UserID]) {
            
        } else {
            [MBProgressHUD showError:@"对方已不是组织架构中的成员"];
            return;
        }
    }
    UIImage *videoImage = [self thumbnailImageForVideo:url atTime:0];
    NSData *videoData = [NSData dataWithContentsOfURL:url];
    
    [[CXmppRequestMgr shareInstance] sendVideoMessage:videoData videoImage:videoImage messageId:nil curUser:self.currentUser member:self.member group:self.group fileName:nil];
    [self deleteVideo];
}
- (void)sendFileWithArray:(NSArray *)array
{
    //    NSArray *array = notice.object;
    
    if (![self.conMgr isAvalableContactWithUserId:self.currentUser.UserID]) {
        [MBProgressHUD showError:@"您已不是组织架构中的成员"];
        return;
    }
    
    
    if (self.group) {
        if ([self.groupMgr isAvalableGroupWithGroupId:self.group.GroupId]) {
            
        } else {
            NSString *error = self.group.groupType == 1 ? @"该讨论组已解散或您已不是该讨论组成员":@"该群已解散或您已不是群成员";
            [MBProgressHUD showError:error];
            return;
        }
    } else {
        if ([self.conMgr isAvalableContactWithUserId:self.member.UserID]) {
            
        } else {
            [MBProgressHUD showError:@"对方已不是组织架构中的成员"];
            return;
        }
    }
    
    for (int i = 0; i < array.count; i ++) {
        CFileModel *fileModel = array[i];
        
        [[CXmppRequestMgr shareInstance] sendFile:fileModel messageId:nil curUser:self.currentUser member:self.member group:self.group];
    }
    
}

- (void)sendImageMessage:(UIImage *)image index:(NSInteger)index
{
    if (![self.conMgr isAvalableContactWithUserId:self.currentUser.UserID]) {
        [MBProgressHUD showError:@"您已不是组织架构中的成员"];
        return;
    }
    
    
    if (self.group) {
        if ([self.groupMgr isAvalableGroupWithGroupId:self.group.GroupId]) {
            
        } else {
            NSString *error = self.group.groupType == 1 ? @"该讨论组已解散或您已不是该讨论组成员":@"该群已解散或您已不是群成员";
            [MBProgressHUD showError:error];
            return;
        }
    } else {
        if ([self.conMgr isAvalableContactWithUserId:self.member.UserID]) {
            
        } else {
            [MBProgressHUD showError:@"对方已不是组织架构中的成员"];
            return;
        }
    }
    
    [[CXmppRequestMgr shareInstance] sendImageMessage:image messageId:nil index:index curUser:self.currentUser member:self.member group:self.group fileName:nil];
    
}
-(void)sendMapImageMessage:(UIImage *)mapImage withLat:(double)lat andLon:(double)lon
{
    if (![self.conMgr isAvalableContactWithUserId:self.currentUser.UserID]) {
        [MBProgressHUD showError:@"您已不是组织架构中的成员"];
        return;
    }
    
    
    if (self.group) {
        if ([self.groupMgr isAvalableGroupWithGroupId:self.group.GroupId]) {
            
        } else {
            NSString *error = self.group.groupType == 1 ? @"该讨论组已解散或您已不是该讨论组成员":@"该群已解散或您已不是群成员";
            [MBProgressHUD showError:error];
            return;
        }
    } else {
        if ([self.conMgr isAvalableContactWithUserId:self.member.UserID]) {
            
        } else {
            [MBProgressHUD showError:@"对方已不是组织架构中的成员"];
            return;
        }
    }
    
    [[CXmppRequestMgr shareInstance] sendMapMessage:mapImage messageID:nil curUser:self.currentUser member:self.member group:self.group latitude:lat longitude:lon];
    

}


#pragma mark chbubumessagecellDelegate
- (CHBubbleMessageType)messageTypeForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    
    //    return (msg.memoryID == _myChildHood.memoryId && msg.relativeType == _myRelativeType) ? CHBubbleMessageTypeSended : CHBubbleMessageTypeReceived;
    return msg.isMine;
}
-(BOOL)ismapForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    if ([msg.fileName hasPrefix:@"location"]) {
        return YES;
    }
    else
    {
        return NO;
    }
}
- (CHBubbleStyle)messageStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = nil;
    if(indexPath.row < [self.messages count])
    {
        msg = [self.messages objectAtIndex:indexPath.row];
        
    }
    
    CHBubbleStyle style;
    switch (msg.messageType) {

        case SNSPMaterialTypeKMessage:
        {
            //NSLog(@"文字类型");
            style = CHBubbleStyleText;
            break;
        }
        case SNSPMaterialTypeKAudio:
        {
            
            style = CHBubbleStyleVoice;
            break;
        }
        case SNSPMaterialTypeKEmotion:
        {
           
            style = CHBubbleStyleEmoticon;
            break;
        }
        case SNSPMaterialTypeKImage:
        {
            
            style = CHBubbleStylePicture;
            break;
        }
        case SNSPMaterialTypeKFile:
        {
            style = CHBubbleStyleFile;
            break;
        }
        case SNSPMaterialTypeKVideo:
        {
            style = CHBubbleStyleVideo;
            break;
        }
        case SNSPShake:
        {
            style = CHBubbleStyleShke;
            break;
        }
        case SNSRedPacket:
        {
            style = CHBubbleStyleRedPacket;
            break;
        }
        default:
            //NSLog(@"未知类型");
            break;
    }
    return style;
}

- (CHMessagesViewTimestampPolicy)timestampPolicy
{
    return CHMessagesViewTimestampPolicyCustom;
}

- (CHAvatarStyle)avatarStyle
{
    return CHAvatarStyleSquare;
}

- (BOOL)hasTimestampForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row>= [self.messages count])
    {
        return NO;
    }
    ChildHoodMessage *curMsg = [self.messages objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        return YES;
    }
    else
    {
        ChildHoodMessage *preMsg = [self.messages objectAtIndex:indexPath.row-1];
        int64_t curMsgTime = [curMsg getMessageGMTTime]/1000/60/5;
        int64_t preMsgTime = [preMsg getMessageGMTTime]/1000/60/5;
        
        if (curMsgTime == preMsgTime) {
            return NO;
        }
    }
    return YES;
}

#pragma mark - Messages view data source
- (int64_t)voiceMessageDBIDForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.messageDBID;
}

- (BOOL)voiceIsPlayForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.isPlayed;
}

-(CGFloat)voiceTimeForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.SoundLenth;
}

- (NSArray *)pictureURIArrayForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    NSString* str = msg.fileUri;
    if(str.length < 3)str = msg.nextFileUri;
    if(str.length < 3)str = nil;
    NSString* str2 = msg.nextFileUri;
    if(str2.length <3) str2 = nil;
    return [NSArray arrayWithObjects:str,str2, nil];
}

- (NSString *)fileNameForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.fileName;
    
}
- (NSString *)fileIdForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    if (self.group) {
        return msg.GroupId;
    } else {
        if (msg.isMine == CHBubbleMessageTypeSended) {
            return msg.MineUserId;
        } else {
            return msg.FriendUserId;
        }
    }
    
}

- (NSString *)chatTypeForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.group) {
        return @"groupChat";
    } else {
        return @"chat";
    }
}
- (NSString *)voiceURIForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.fileUri;
}

- (NSString *)senderNameForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    //    NSLog(@"%@",msg.fromName);
    return msg.fromName;
}

- (NSString *)senderTitleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    
    return msg.title;
}

- (NSString *)textForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.messageContent;
}

- (NSDate *)timestampForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    //NSLog(@"%@",[msg getMessageTime]);
    return [msg getMessageTime];
}

- (NSString *)avatarImageURIForReceivedMessageRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    //    return msg.senderPortraitImageUri;
    ChildHoodMessage *chMessage = self.messages[indexPath.row];
    if (self.group) {
        return [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:chMessage.MineUserId];
    } else {
        return [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:chMessage.FriendUserId];
    }
    
}

- (NSString *)avatarImageURIForSendedMessageRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    NSString *uri = [[ChildHoodService defaultService].childHoodMemory getProfilePictureUri];
    //    return uri;
    ChildHoodMessage *chMessage = self.messages[indexPath.row];
    return  [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:chMessage.MineUserId];
}

- (int32_t)messageStatusForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    
    return msg.messageStatus;
}

- (uint32_t)memoryIDForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.memoryID;
}

- (BOOL)isNoticeForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    if (msg.type == SNSPMessageTypeKNoticeType) {
        return YES;
    }
    return NO;
}


- (NSString *)stringFromDate:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy_MM_dd_HH_mm_ss"];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    return destDateString;
}

#pragma mark --ChatToolDelegate--

-(void)voicebtnDown:(id)sender
{
    self.IsVoiceBtnUp = NO;
    self.IsGettingSerTime = YES;
    self.sendType = SNSPMaterialTypeKAudio;
    
    [[CHSAudioPlayer sharedInstance] stopSound];
    
    __block NSIndexPath *redIndexPath = nil;
    
    [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *obj, NSUInteger idx, BOOL *stop) {
        
        if (obj.isPlayed == MessageSoundPlaying) {
            obj.isPlayed = MessageSoundPlayed;
            redIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
            *stop = YES;
        }
    }];
    
    [self.tableView reloadData];
    if (redIndexPath != nil) {
        
    }
    
    NSString *timeStamp = [UIUtil getCurrentTimeStamp];
    if (self.group) {
        NSString *filename = [NSString stringWithFormat:@"%@___%@___%@.wav",timeStamp,self.currentUser.UserID,timeStamp];
        self.tempFileName = filename;
        [_recorder startRecordWithPath:[[[ChildHoodService defaultService] groupUploadSoundPathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:self.tempFileName]];
    } else {
        
        NSString *filename = [NSString stringWithFormat:@"%@___%@.wav",timeStamp,timeStamp];
        self.tempFileName = filename;
        [_recorder startRecordWithPath:[[[ChildHoodService defaultService] personalUploadSoundPathWithUserId:self.currentUser.UserID] stringByAppendingPathComponent:self.tempFileName]];
    }
    
}
- (void)voicebtnUpInside:(id)sender
{
    if (![self.conMgr isAvalableContactWithUserId:self.currentUser.UserID]) {
        [MBProgressHUD showError:@"您已不是组织架构中的成员"];
        return;
    }
    
    if (self.group) {
        if ([self.groupMgr isAvalableGroupWithGroupId:self.group.GroupId]) {
            
        } else {
            NSString *error = self.group.groupType == 1 ? @"该讨论组已解散或您已不是该讨论组成员":@"该群已解散或您已不是群成员";
            [MBProgressHUD showError:error];
            return;
        }
    } else {
        if ([self.conMgr isAvalableContactWithUserId:self.member.UserID]) {
            
        } else {
            [MBProgressHUD showError:@"对方已不是组织架构中的成员"];
            return;
        }
    }
    
    [_recorder stopRecordWithCompletionBlock:^(NSInteger timeLenth){
        
        [[CXmppRequestMgr shareInstance] sendVoiceMessageWihtCurUser:self.currentUser messageId:nil member:self.member group:self.group fileName:self.tempFileName timeLenth:timeLenth];
        
    }];
}
- (void)voicebtnUpOutside:(id)sender
{
    
    [_recorder finishCancelled];
}
- (void)voicebtnDragExit:(id)sender
{
    
    [_recorder cancelled];
}
- (void)voicebtnDragEnter:(id)sender
{
    
    [_recorder recording];
}


- (int)checkTextCount:(NSString *)text
{
    int length = [self convertToInt:text];
    //    if (length>kMaxTextLength) {
    //        return NO;
    //    }
    //    return YES;
    return length;
}

-  (int)convertToInt:(NSString*)strtemp {
    
    int strlength = 0;
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
    }
    return (strlength+1)/2;
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

-(UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    return thumbnailImage;
}
-(void)deleteVideo
{
    if (self.videoUrl) {
        NSString *filePath = [[self.videoUrl absoluteString] stringByReplacingOccurrencesOfString:@"file://" withString:@""];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            NSError *error = nil;
            [fileManager removeItemAtPath:filePath error:&error];
            
            if (error) {
                NSLog(@"deleteAllVideo删除视频文件出错:%@", error);
            }
        }
        
    }
}
- (BOOL)handleVideoWithMessage:(ChildHoodMessage*)message
{
    NSString *fileId;
    NSString *path;
    if (message.GroupId.length > 3) {
        fileId = message.GroupId;
        if (message.isMine == CHBubbleMessageTypeReceived) {
            path = [[[ChildHoodService defaultService] groupDownloadVideoPathWithGroupId:fileId] stringByAppendingPathComponent:message.fileName];
        } else {
            path = [[[ChildHoodService defaultService] groupUploadVideoPathWithGroupId:fileId] stringByAppendingPathComponent:message.fileName];
        }
        
    } else {
        if (message.isMine == CHBubbleMessageTypeReceived) {
            fileId = message.FriendUserId;
            path = [[[ChildHoodService defaultService] personalDownloadVideoPathWithUserId:fileId] stringByAppendingPathComponent:message.fileName];
        } else {
            fileId = message.MineUserId;
            path = [[[ChildHoodService defaultService] personalUploadVideoPathWithUserId:fileId] stringByAppendingPathComponent:message.fileName];
        }
    }
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
    if (data && data.length >= message.fileLenth.longLongValue) {
        return YES;
    }
    return NO;
    
}

@end

//-(BOOL)isMessageExist:(ChildHoodMessage *)memory
//{
//    BOOL isExist = NO;
//    @synchronized(self.messages)
//    {
//        for(ChildHoodMessage *index in self.messages)
//        {
//            if(index.messageDBID == memory.messageDBID)
//            {
//                isExist = YES;
//                break;
//            }
//        }
//    }
//    return isExist;
//}
